package com.example.mybatisplus.dynamic;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

public class MultipleDataSource extends AbstractRoutingDataSource {

    private static final ThreadLocal<String> currentLookupKey = new InheritableThreadLocal<>();

    public MultipleDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return currentLookupKey.get();
    }

    public static void setCurrentLookupKey(String lookupKey) {
        currentLookupKey.set(lookupKey);
    }

    public static void clearLookupKey() {
        currentLookupKey.remove();
    }
}